#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QFileDialog>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QMenuBar* menuBar = this->menuBar();

    QMenu* menu = new QMenu("文件");
    menuBar->addMenu(menu);
    QAction* act1 = new QAction("打开");
    QAction* act2 = new QAction("保存");
    menu->addAction(act1);
    menu->addAction(act2);

    text = ui->plainTextEdit;
    connect(act1,&QAction::triggered,this,&MainWindow::handleAction1);
    connect(act2,&QAction::triggered,this,&MainWindow::handleAction2);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleAction1()
{
    QString path = QFileDialog::getOpenFileName(this);
    QStatusBar* status = this->statusBar();

    status->showMessage(path);
    text->setPlainText(path);

    QFile file(path);
    bool ret = file.open(QIODevice::ReadOnly);
    if(!ret)
    {
        status->showMessage(path+"打开失败");
        return;
    }
    QString txt = file.readAll();

    file.close();
    text->setPlainText(txt);
}

void MainWindow::handleAction2()
{
    QString path = QFileDialog::getSaveFileName(this);
    QStatusBar* status = this->statusBar();

    status->showMessage(path);

    QFile file(path);
    bool ret = file.open(QFile::WriteOnly);
    if(!ret)
    {
        status->showMessage(path + "打开失败");
        return;
    }

    const QString& txt = text->toPlainText();
    file.write(txt.toUtf8());

    file.close();
}


void MainWindow::on_pushButton_clicked()
{
    QString path = QFileDialog::getOpenFileName(this);

    QFileInfo fileInfo(path);

    qDebug()<<fileInfo.fileName()<<fileInfo.suffix();
}
